<template>
    <div>
        <div class="apibody" name="apibody">
            接口名 <el-input v-model="form.apiname" class="inp"></el-input>
            接口路径 <el-input v-model="form.apipath" class="inp"></el-input>
            接口域名 <el-input v-model="form.api_url" class="inp"></el-input>
            <div style="margin-top: 10px;">
                请求类型 
                <el-select v-model="form.ApiType" placeholder="请选择请求类型">
                    <el-option label="json"  value="application/json;charset=UTF-8"></el-option>
                    <el-option label="from" value="application/x-www-form-urlencoded"></el-option>
                    <el-option label="RAW" value="application/json"></el-option>
                    <el-option label="XML" value="text/xml"></el-option>
                </el-select>
                请求方式 
                <el-select v-model="form.ApiMethod" placeholder="请选择请求方式">
                    <el-option label="Post" value= 0></el-option>
                    <el-option label="GET" value= 1></el-option>
                    <el-option label="PUT" value= 2></el-option>
                    <el-option label="Head" value= 3></el-option>
                    <el-option label="DELETE" value= 4></el-option>
                </el-select>
                请求协议 
                <el-select v-model="form.Protocol" placeholder="请选择请求方式">
                    <el-option label="HTTP" value="http"></el-option>
                    <el-option label="HTTPS" value="Https"></el-option>
                </el-select>
            </div>
        <!-- </div> -->
        <el-divider></el-divider>
        <!-- <div class="api_head"> -->
        <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="请求Haeder" name="head">
                <!-- <Head></Head> -->
                <el-row>
                    <el-col :span="4">名称</el-col>
                    <el-col :span="4">值</el-col>
                    <el-col :span="4">描述</el-col>
                    <el-col :span="6">操作</el-col>
                </el-row>
                <el-divider></el-divider>
                <div class="info">
                <el-row>
                    <div v-for="item in form.headform">
                        <el-input v-model="item.Key" placeholder="Content-Type" style="width: 295px"></el-input>
                        <el-input v-model="item.Value" placeholder="application/x-www-form-urlencoded" style="width: 295px"></el-input>
                        <el-input v-model="item.Desc" placeholder="Describe" style="width: 300px"></el-input>
                        <el-button @click.prevent="removeDomain(item)"><i class="fa fa-trash-o fa-lg"></i></el-button>
                    </div>
                </el-row>
                </div>
                <div>
                    <el-divider></el-divider>
                    <el-button @click="addDomain">Add Head</el-button>
                </div>
            </el-tab-pane>
            <el-tab-pane label="请求参数" name="param">
                <!-- <Parms></Parms> -->
                <el-row>
                    <el-col :span="4">字段名</el-col>
                    <el-col :span="4">数据类型</el-col>
                    <el-col :span="4">值</el-col>
                    <el-col :span="4">描述</el-col>
                    <el-col :span="4">操作</el-col>
                </el-row>
                <el-divider></el-divider>
                <div class="info">
                    <el-row>  
                        <div v-for="(item, index) in form.par" >
                            <el-input v-model="item.Key" placeholder="Key" style="width: 290px"></el-input>
                            <el-select v-model="item.Type" @change="test" placeholder="请选择请求方式" style="width: 295px">
                            <el-option v-for="i,j in Types" :label="i.Keys" :value="i.Values"></el-option>
                            </el-select>
                           <!--  <el-input v-model= "item.Value" style="width: 300px" placeholder="value"></el-input> -->
                            <el-input v-if="item.Type=='File'" type="file" v-model= "item.Value" style="width: 300px" ref="inputer" @change="uploading($event)" multiple placeholder="file"></el-input>
                            <el-input v-if="item.Type=='Md5'" v-model= "item.Value" style="width: 300px" placeholder="输入需要进行md5加密的内容"></el-input>
                            <el-input v-if="item.Type=='TimeStamp'" v-model= "item.Value" style="width: 300px" placeholder="时间戳"></el-input>
                            <el-input v-if="item.Type=='Random'" v-model= "item.Value" style="width: 300px" placeholder="start,end"></el-input>
                            <el-input v-if="item.Type=='String'" v-model= "item.Value" style="width: 300px" placeholder="value"></el-input>
                            <el-input v-if="item.Type=='Int'" v-model= "item.Value" style="width: 300px" placeholder="整数"></el-input>
                            <el-input v-if="item.Type =='StrRandom'" v-model= "item.Value" style="width: 300px" placeholder="输入随机字符长度"></el-input>
                            <el-input v-if="item.Type =='Base64'" v-model= "item.Value" style="width: 300px" placeholder="输入Base64内容"></el-input>

                            <!-- <el-input v-if="item.Type=='File'" type="file" v-model= "item.Value" style="width: 300px" ref="inputer" multiple accept="image/png,image/jpeg,image/gif,image/jpg"></el-input> -->

                            <el-input v-model="item.Desc" placeholder="Desc" style="width: 290px"></el-input>
                            <el-button  @click.prevent="removePar(item)"><i class="fa fa-trash-o fa-lg"></i></el-button>
                        </div>
                    </el-row>
                </div>
                <div>
                    <el-divider></el-divider>
                    <el-row>
                        <h3>加密</h3> 
                        <br>
                        <template>
                            <el-radio v-model="EncryEncode" label="1">造字</el-radio>
                            <el-radio v-model="EncryEncode" label="2">写字先生</el-radio>
                        </template>
                        <el-divider></el-divider>
                        <h3>代理</h3>
                        <br>
                        <el-switch
                            v-model="IsProxy"
                            active-color="#13ce66"
                            inactive-color="#ff4949">
                        </el-switch>
                    </el-row>
                    
                    <el-divider></el-divider>
                    <el-button @click="addPar">新增参数</el-button> 
                </div>
            </el-tab-pane>
        </el-tabs>
        </div>
        <div>
            <el-button @click="Run"><li class="fa fa-send"></li> Send</el-button>
        </div>

        <div class="res" v-show="res_show">
            <!-- <el-divider></el-divider> -->
            <!-- {{response}} -->
            <H5>解密后返回结果</H5>
            <pre>{{ DeMsg}}</pre>
            <H5>解密前返回结果</H5>
            <pre>{{ JSON.stringify(response, null, 4)}}</pre>
            
        </div>
    </div>
    
</template>

<script>
import Head from './head';
import Parms from './params';
import axios from 'axios';
import Getmd5 from 'js-md5';
import {shijianchuo,formatDate,timetostamp,stamptotime} from '../../js/dates';
import {GetRandomNum,GetRandomStr,Base64Encode,Base64Decode,DictSort,DictSortStr,XorEncodeStr,XorDecodeStr,XorDecodeStrByte} from '../../js/tools';
axios.defaults.timeout = 5000;
export default {
    name: 'TestHome',
    data(){
        return { 
            activeName:"param",
            file:"",
            res_show:false,
            response: {},
            IsIos : false,
            form:{ 
                Protocol:"http",
                par:[{Key:"userId",Type:"String",Value:"3607804",Desc:"desc"},
                // {Key:"sign",Type:"Md5",Value:"founder+$+founder",Desc:"new"}
                ],
                
                headform:[
                    // {
                    // Key:"Host",
                    // Value:"",
                    // Desc:""
                    // },
                    // {
                    // Key:"Referer",
                    // Value:"",
                    // Desc:""
                    // },
                    {
                        Key:"Content-Type",
                        Value:"",
                        Desc:"请求方式"
                    }
                ],
                apipath:"/font/getUserInfo.json",
                apiname:"test",
                api_url:"hw.fzshouji.com",
                ApiMethod: 0,
                ApiType: "application/json;charset=UTF-8",
            },
            Types:[
                {Keys:"MD5加密",Values:"Md5"},
                {Keys:"时间戳",Values:"TimeStamp"},
                {Keys:"随机数",Values:"Random"},
                {Keys:"整数",Values:"Int"},
                {Keys:"字符串",Values:"String"},
                {Keys:"文件",Values:"File"},
                {Keys:"Base64加密",Values:"Base64"},
                {Keys:"随机字符串",Values:"StrRandom"}
            ],
            EncryEncode: "1",
            DeMsg: {},
            IsProxy:false,
            formdata:new FormData(),
        }
    },
    components: {Head,Parms},
    mounted:function () {
    },//mounted
    methods: {
        test(t){
            console.log(t);
        },
        strTojson(msg) {
            var  tt;
            try {
                tt = JSON.parse(msg);
            } catch(e) {
                console.log("json解析失败",e);
            }
            var res = JSON.stringify(tt,null,"\t");
            return res
        },
        PubParams(){
            var ClientSW = "5.5.2"
            var Client_type = "app"
            var now = shijianchuo();

            let par = {"sys": "ADR10.0.1", "clientSW": ClientSW, "ptype": "Product: starqltezc, CPU_ABI: armeabi-v7a, MODEL: SM-G9600, SDK: 28, BRAND: samsung, MANUFACTURER: samsung, USER: dpi", "client_type": Client_type, "t": now, "platform": "0", "channelNumber": "huawei", "deviceID": "f4b9bcfd8218151d993bbbfc9f0f7dccda4251c4lx"} 
            if (this.IsIos){
                par = {"sys": "iOS13.2", "clientSW": ClientSW, "ptype": "Iphone7Plus", "client_type": Client_type, "t": now, "platform": "1", "channelNumber": "26","deviceID":"2115274cea142d724976442dcc90802f"}
            }
            return par
        },
        handleClick(tab, event) {
        },
        childByValue: function (childValue) {
            // childValue就是子组件传过来的值
            this.name = childValue
        },
        uploading(f){
             this.file = event.target.files[0];//获取文件
             console.log(this.file);
        },
        Post(urls,datas,header){
            let ret = '';
            if (header["Content-Type"] === "application/x-www-form-urlencoded"){
                for (let it in datas) {
                    ret += encodeURIComponent(it) + '=' + encodeURIComponent(datas[it]) + '&';
                }
                datas = ret;
            }
            var tunnel = require('tunnel');
            var tunnelingAgent = tunnel.httpOverHttp({
                proxy: {
                    host: '192.168.248.168',
                    port: 8001
                }
            });

            // axios({
            //     url: urls,
            //     method: 'post',
            //     // proxy: this.IsProxy,
            //     data:datas,
            //     headers:header,
            //     // agent: tunnelingAgent,
            //     proxy: {
            //         host: '192.168.248.168',
            //         port: 8001
            //     }
            //     // httpAgent: tunnel.httpOverHttp({proxy: {host: '192.168.248.168', port: '8001'}}),
            //     // httpsAgent: tunnel.httpsOverHttp({proxy: {host: '192.168.248.249', port: '8001'}})
            // }).then(res => {
            //     console.log(res)
            // })
            // return
            axios.post(urls,datas,{proxy: {
                    host: '192.168.248.168',
                    port: 8001
                },"headers":header}).then(
                res => {
                    res => res;
                    if (res == undefined){
                        this.$message.error("接口不存在")
                    }else{
                        var data = res.data;
                        var request = res.request;
                        var status = res.status;
                        var config = res.config;
                        var header = res.headers["encrypt-control"]
                        this.response = res;//JSON.parse(res);
                        this.res_show = true;
                        if (status == 200){
                            if (header == "open" && (request.responseURL.includes("hw.") || request.responseURL.includes("hwdev."))) {
                                // var xor = XorDecodeStr(data,"w1VE9CrWU0lANcrQPoQ6c9PMRx");
                                const b_data = Buffer.from(data);
                                const b_key = Buffer.from("w1VE9CrWU0lANcrQPoQ6c9PMRx");
                                var b_xor = XorDecodeStrByte(b_data,b_key);
                                var tmp = this.strTojson(Base64Decode(b_xor));
            
                                var xor = XorDecodeStrByte(data,"w1VE9CrWU0lANcrQPoQ6c9PMRx");
                                var bs = Base64Decode(xor);
                                var jsr = JSON.stringify(bs, null, 4);
                                var ss = JSON.parse(jsr);
                                this.DeMsg = tmp;
                                res["xor_data"] = ss;
                            }else{
                                this.$message(JSON.stringify(data, null, 4));
                            }
                            
                        }
                        // else if (status == 500){
                        //     console.log(500);
                        //     this.$message.error(JSON.stringify(data, null, 4));
                        // }
                    }
                }
            ).catch(
                (err) => {
                    this.$message.error("请求发送失败:\n"+err);
                    this.response = {};
                    this.res_show = false;
                }
            )
        },
        Md5(msg){
            var res = Getmd5(msg);            
            return res;
        },
        Get(url,data,header){
            var ret = '';
            for (let it in data) {
                ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it])+"&";
            }
            data = ret.substring(0,ret.length-1);
            axios.get(url+"?"+data,header).then(
                res => {
                    res => res;
                    if (res == undefined){
                        this.$message.error("接口不存在")
                    }else{
                        var data = res.data;
                        var status = res.status;
                        if (status == 200){
                            this.$message(JSON.stringify(data, null, 4));
                        }else{
                            this.$message.error(res);
                        }
                    }

            }).catch(
                (err) => {
                    this.$message.error("请求发送失败:\n"+err);
                    this.response = {};
                    this.res_show = false;
                }
            )
        },
        Put(url,data,header){
            axios.put(url,data,header).then(response => (
                console.log(response)
            )).catch(
                (err) => {
                    this.$message.error("请求发送失败:\n"+err);
                    this.response = {};
                    this.res_show = false;
                }
            )
        },
        Del(url,data,header){

        },
        Run() {
            var that = this;
            var form = that.form;
            var par_tmp = form.par;
            let data = this.PubParams();;
            var dataform = {};
            var method = form.ApiMethod;
            var url = form.Protocol+"://"+form.api_url+form.apipath;
            var header_tmp = form.headform;
            var headers = {};
            var is_new = false;
            var md5str = {};
            var is_sj = false;
            for (var i = header_tmp.length - 1; i >= 0; i--) {

                if (header_tmp[i].Key != ""){
                    headers[header_tmp[i].Key] = header_tmp[i].Value
                }
            }
            // headers["Referer"] = form.api_url
            // headers["Host"] = form.api_url
            headers["Content-Type"] = form.ApiType
            // that.$refs.inputer.submit();

            
            for (var i = par_tmp.length - 1; i >= 0; i--) {
                var keys = par_tmp[i].Key;
                var values = par_tmp[i].Value;
                if (par_tmp[i].Key == ""){
                    continue
                }
                else if (par_tmp[i].Type === 'File'){
                    headers["Content-Type"] = "multipart/form-data"
                    data[keys] = that.file;
                    that.formdata.append(keys,that.file);

                }else if (par_tmp[i].Type === 'Md5'){
                    if (par_tmp[i].Desc != "new") {
                        data[keys] = Getmd5(par_tmp[i].Value);
                        that.formdata.append(keys,Getmd5(values));
                    }else{
                        is_new = true;
                        md5str[keys] = par_tmp[i].Value
                    }
                    
                }else if (par_tmp[i].Type === 'Int'){
                    data[keys] = Number(par_tmp[i].Value);
                    that.formdata.append(keys,Number(par_tmp[i].Value));
                }else if (par_tmp[i].Type === 'StrRandom'){
                    data[keys] = GetRandomStr(par_tmp[i].Value);
                    that.formdata.append(keys,GetRandomStr(par_tmp[i].Value));
                }else if (par_tmp[i].Type === 'Random'){
                    var tmp = par_tmp[i].Value.split(",");
                    var res = GetRandomNum(tmp[0],tmp[1]);
                    data[keys] = res;
                    that.formdata.append(keys,res);
                }else if (par_tmp[i].Type === 'TimeStamp'){
                    data[keys] = shijianchuo();
                    that.formdata.append(keys,shijianchuo());
                }else if (par_tmp[i].Type === 'Base64'){
                    data[keys] = Base64Encode(par_tmp[i].Value);
                    that.formdata.append(keys,Base64Encode(par_tmp[i].Value));
                }
                else {
                    data[keys] = values;
                    that.formdata.append(keys,values);
                }
                
            }


            if (is_new){
                var tmp;
                var msg = "";
                var key = Object.keys(md5str)[0];
                tmp = md5str[key].split("+");

                for (var i = tmp.length - 1; i >= 0; i--) {
                    if (tmp[i].indexOf("$" ) > -1){
                        var tkey = tmp[i].replace("$","");
                        msg += (DictSortStr(data))
                    }else{
                        msg +=tmp[i]
                    }
                } 
                // data[key] = Getmd5(msg)
                that.formdata.append(key,Getmd5(msg));
            }

            data = DictSort(data)

            
            if (that.EncryEncode == "1"){
                var msg = "founder"+DictSortStr(data)+"founder";
                data["sign"] = Getmd5(msg)
                var jstr = JSON.stringify(data, null, 0);
                var bs = Base64Encode(jstr);
                var xor = XorEncodeStr(bs,"NPHJxgRtCXhai08iBW0pV52PEw");
                dataform["p"] = xor 
                that.formdata.append("p",xor);
            }else{
                dataform = data
            }

            if (form.ApiMethod == 0){
                if (headers["Content-Type"] == "multipart/form-data") {
                    that.Post(url,that.formdata,headers);
                }else{
                    that.Post(url,dataform,headers);
                }
            }else if (form.ApiMethod == 1){
                that.Get(url,data,headers);
            }else if (form.ApiMethod == 2){
                that.Put(url,data,headers);
            }else if (form.ApiMethod == 3){
                that.Del(url,data,headers);
            }
            
            
            
            
            
        },
        removeDomain(item) {
            var index = this.form.headform.indexOf(item)
            if (index !== -1) {
              this.form.headform.splice(index, 1)
            }
        },
        addDomain() {
            this.form.headform.push({
                Key:"",
                Value:"",
                Desc:""
            });
        }, 
        addPar() {
            this.form.par.push({
              Key:"",Type:"",Value:"",Desc:""}
            );
        }, 
        removePar(item) {
            var index = this.form.par.indexOf(item)
            if (index !== -1) {
              this.form.par.splice(index, 1)
            }
        }
    }
}
</script>

<style scoped>
.api_head{
    /*height: 300px;*/
    /*text-align: center;*/
    background-color: rgba(186, 188, 187, 0.21);
}
.inp{
    width: 400px;
}
.apibody{
    background-color: rgba(186, 188, 187, 0.21);
    margin-bottom: 10px;
    padding: 10px;
}
.info{
    height:150px;
    overflow:auto
    /*background-color: orange;*/
}
.name{
    right: 10px;
}
.res{
    position: relative;
    overflow-y:auto;
    overflow: auto;
    height: 300px;
    background-color: rgba(11, 47, 247, 0.07);
}
</style>